import axios from 'axios';
import { ElMessage } from 'element-plus';

let router;
let apiClient;

export function setAxiosInterceptors(customRouter) {
    router = customRouter;

    apiClient = axios.create({
        baseURL: 'http://localhost:8080/api/exam',
        timeout: 5000,
    });

    // 请求拦截器
    apiClient.interceptors.request.use(
        (config) => {
            const token = localStorage.getItem('token');
            if (token) {
                config.headers['Authorization'] = `Bearer ${token}`;
            }
            return config;
        },
        (error) => Promise.reject(error)
    );

    // 响应拦截器
    apiClient.interceptors.response.use(
        (response) => {
            const url = response.config.url;

            // 如果是登录接口，跳过 token 更新逻辑
            if (url.includes('/login')) {
                return response;
            }

            // 检查响应头是否有新的 token
            const newToken = response.headers['authorization'];

            if (newToken) {
                const cleanToken = newToken.replace('Bearer ', ''); // 去掉 Bearer 前缀
                const currentToken = localStorage.getItem('token');

                if (cleanToken !== currentToken) {
                    localStorage.setItem('token', cleanToken); // 存储干净的 token
                }
            }
            return response;
        },
        (error) => {
            if (error.response?.status === 401) {
                localStorage.removeItem('token');
                router.push('/login');
                ElMessage.error('登录已过期，请重新登录');
            }
            return Promise.reject(error);
        }
    );

    return apiClient;
}
export { apiClient };

export default {
    // 试卷相关
    getAllPapers() {
        return apiClient.get('/papers');
    },
    getPaperById(id) {
        return apiClient.get(`/papers/${id}`);
    },
    getPaperDetails(id) {
        return apiClient.get(`/papers/${id}/details`);
    },
    createPaper(paper) {
        return apiClient.post('/papers', paper);
    },
    deletePaper(id) {
        return apiClient.delete(`/papers/${id}`);
    },

    // 出题规则
    getRules() {
        return apiClient.get(`/rules/full`);
    },
    addPaperRule(rule) {
        return apiClient.post(`/rules/full`, rule);
    },
    getRuleById(ruleId) {
        return apiClient.get(`/rules/full/${ruleId}`);
    },
    updatePaperRule(ruleId, rule) {
        return apiClient.put(`/rules/full/${ruleId}`, rule);
    },
    deleteRule(ruleId) {
        return apiClient.delete(`/rules/full/${ruleId}`);
    },

    // 题库管理
    getAllBanks() {
        return apiClient.get('/banks');
    },
    getBankById(id) {
        return apiClient.get(`/banks/${id}`);
    },
    createBank(bank) {
        return apiClient.post('/banks', bank);
    },
    deleteBank(id) {
        return apiClient.delete(`/banks/${id}`);
    },
    updateBank(bank) {
        return apiClient.put(`/banks/${bank.id}`, bank);
    },

    // 题目获取
    getQuestionsByBankAndType(bankId, type) {
        return apiClient.get('/questions', {
            params: {
                bankId: bankId || undefined, // 自动过滤空字符串和 undefined
                type: type || undefined
            }
        });
    },

    // 用户管理
    getUsers() {
        return apiClient.get('/users');
    },
    updateUser(id, userData) {
        return apiClient.put(`/users/${id}`, userData);
    },
    deleteUser(id) {
        return apiClient.delete(`/users/${id}`);
    },
    getCurrentUser() {
        return apiClient.get('/users/me');
    },

    captcha() {
        return apiClient.get('/captcha');
    },

    login(username, password, captcha, imgToken) {        
        return apiClient.post('/login', {
            username,
            password,
            captcha,
            imgToken
        });
    },
    register(username, password) {
        return apiClient.post('/register', {
            username,
            password
        });
    },



    // 获取试卷题目
    getPaperQuestions(paperId) {
        return apiClient.get(`/papers/${paperId}/questions`);
    },

    // 提交试卷
    submitPaper(paperId, answers) {
        return apiClient.post(`/papers/${paperId}/submit`, answers);
    },

    // 题目管理
    getAllQuestions() {
        return apiClient.get('/questions/all');
    },
    getQuestionById(id) {
        return apiClient.get(`/questions/${id}`);
    },
    createQuestion(question) {
        return apiClient.post('/questions', question);
    },
    updateQuestion(question) {
        return apiClient.put(`/questions/${question.id}`, question);
    },
    deleteQuestion(id) {
        return apiClient.delete(`/questions/${id}`);
    }
};